package com.controller;

import com.annotation.LoginRequired;
import com.common.Result;
import com.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器，演示 Token 认证的使用
 */
@RestController
@RequestMapping("/api/user")
public class UserController {


    @Autowired
    private TokenUtils tokenUtils;

    /**
     * 登录接口
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");

        // 验证用户名和密码（实际项目中应调用服务层验证）
        if (!"admin".equals(username) || !"password".equals(password)) {
            return Result.fail("用户名或密码错误");
        }

        // 生成 Token
        String token = tokenUtils.generateToken(username);

        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("tokenType", "Bearer");
        result.put("expiresIn", tokenUtils.getRemainingTime(token) / 1000); // 转换为秒
        result.put("user", Map.of("username", username, "role", "admin"));

        return Result.success(result);
    }

    /**
     * 登出接口
     */
    @PostMapping("/logout")
    @LoginRequired
    public Result<Void> logout(@RequestHeader("Authorization") String token) {
        // 移除 Bearer 前缀
        String cleanToken = token.replace("Bearer ", "");
        tokenUtils.logout(cleanToken);
        return Result.success();
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/userinfo")
    @LoginRequired
    public Result<Map<String, Object>> getUserInfo(@RequestHeader("Authorization") String token) {
        // 移除 Bearer 前缀
        String cleanToken = token.replace("Bearer ", "");
        String username = tokenUtils.getUserIdFromToken(cleanToken);

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("username", username);
        userInfo.put("role", "admin");
        userInfo.put("permissions", new String[]{"user:read", "user:write", "admin:manage"});

        return Result.success(userInfo);
    }

    /**
     * 刷新 Token
     */
    @PostMapping("/refresh")
    @LoginRequired
    public Result<Map<String, Object>> refreshToken(@RequestHeader("Authorization") String token) {
        // 移除 Bearer 前缀
        String cleanToken = token.replace("Bearer ", "");
        String newToken = tokenUtils.refreshToken(cleanToken);

        Map<String, Object> result = new HashMap<>();
        result.put("token", newToken);
        result.put("tokenType", "Bearer");
        result.put("expiresIn", tokenUtils.getRemainingTime(newToken) / 1000);

        return Result.success(result);
    }
}
